#include "Thread.hpp"
#include "BlockQueue.hpp"
#include <vector>
#include <unistd.h>
#include <memory>
#include "Task.hpp"
#include <random>

using namespace ns_thread;
using namespace ns_bq;

using blockqueue_t = BlockQueue<Task>;

void Product(blockqueue_t &args)
{
    std::cout << "enter product" << std::endl;
    srand(time(nullptr));
    while (1)
    {
        sleep(1);
        int a = rand() % 10 + 1;
        usleep(1234);
        int b = rand() % 10 + 1;
        Task t(a, b);
        args.Push(t);
        std::cout << "Productor->" << t.Add() << std::endl;

    }
}

void Consume(blockqueue_t &args)
{
    while (1)
    {
        sleep(1);
        Task t;
        args.Pop(&t);
        t.Excute();
        std::cout << "Consumer->" << t.Result() << std::endl;

    }
}
void StartComm(std::vector<Thread<blockqueue_t>> *threads, int nums, blockqueue_t &bq, func_t<blockqueue_t> func)
{
    if(func == nullptr)
    {
        std::cerr << "func nullptr!!!" <<std::endl;
        return;
    }
    for (int i = 0; i < nums; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        threads->emplace_back(func, bq, name);
        threads->back().start();
    }
}

void StartProductor(std::vector<Thread<blockqueue_t>> *threads, int nums, blockqueue_t &bq)
{
    StartComm(threads, nums, bq, Product);
}

void StartConsumer(std::vector<Thread<blockqueue_t>> *threads, int nums, blockqueue_t &bq)
{
    StartComm(threads, nums, bq, Consume);
}

void WaitAll(std::vector<Thread<blockqueue_t>>& threads)
{
    for (auto& thread : threads)
    {
        thread.Join();
    }
}

int main()
{
    blockqueue_t *bq = new blockqueue_t(5);
    std::vector<Thread<blockqueue_t>> threads;
    StartProductor(&threads, 1, *bq);
    StartConsumer(&threads, 1, *bq);

    WaitAll(threads);
    
    return 0;
}
